package form

import (
	"errors"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

const DrugPageConfigKey = "@#sfesd#123"

type DrugSubmitForm struct {
	Number   string   `form:"number" json:"number" validate:"required" chn:"报告编号"`
	Title    string   `form:"title" json:"title" validate:"required" chn:"药品名称"`
	Category string   `form:"category" json:"category" validate:"required" chn:"药品类型"`
	Risk     []string `form:"risk[]" json:"risk" validate:"required" chn:"风险累及系统"`
	Remark   string   `form:"remark" json:"remark" chn:"风险描述"`
	Sign     string   `form:"sign" json:"sign" validate:"required"`
	Annexes  []string `form:"annexes[]" json:"annexes"`
}

func (form *DrugSubmitForm) Valid() error {
	db := util.GetMysqlPool().Handler()
	if db.Where("number = ?", form.Number).First(&entity.DrugReport{}).RowsAffected > 0 {
		return errors.New(form.Number + " 报告已提交")
	}

	if !util.VerifyMd5Sign(form.Sign, DrugPageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

type ReportDrugAnnexForm struct {
	Number   string `form:"number" validate:"required" chn:"报告编号"`
	Sign     string `form:"sign" validate:"required"`
	Filename string `form:"filename" validate:"required"`
}

func (form *ReportDrugAnnexForm) Valid() error {
	if !util.VerifyMd5Sign(form.Sign, DrugPageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

func (form *ReportDrugAnnexForm) UploadAnnex(ctx *gin.Context) (string, error) {
	folder := util.CreateDir("storage/annexes/" + time.Now().Format("2006/01/02") + "/" + form.Number)
	file, err := ctx.FormFile("file")
	if err == nil {
		if file.Size > 1024*1024*16 {
			return "", errors.New("上传素材不能大于2M")
		}
		ext, _ := util.GetImgExt(file)
		filename := filepath.Join(folder, form.Filename+ext)
		if err := ctx.SaveUploadedFile(file, filename); err == nil {
			timeUnix := time.Now().Unix()
			return filepath.ToSlash(filename[8:]) + "?" + strconv.FormatInt(timeUnix, 10), nil
		}
	}

	return "", err
}

/*func (form *DrugSubmitForm) UploadAnnexes(ctx *gin.Context, pid uint) {
	if ff, err := ctx.MultipartForm(); err == nil {
		db := util.GetMysqlPool().Handler()
		if files, ok := ff.File["upload[]"]; ok {
			folder := util.CreateDir("storage/annexes/" + time.Now().Format("2006/01/02"))
			for _, file := range files {
				UUID := uuid.NewV4()
				filename := filepath.Join(folder, UUID.String()+path.Ext(file.Filename))
				if err := ctx.SaveUploadedFile(file, filename); err == nil {
					db.Create(&entity.DrugAnnex{Pid: pid, Src: filepath.ToSlash(filename[8:]),})
				} else {
					fmt.Println(err)
				}
			}
		}
	}
}*/

func (form *DrugSubmitForm) Submit(ctx *gin.Context, user entity.User) error {
	db := util.GetMysqlPool().Handler()
	category, _ := strconv.Atoi(form.Category)
	report := entity.DrugReport{
		Title:         form.Title,
		CategoryRefer: category,
		RiskRefer:     strings.Join(form.Risk, ","),
		Number:        form.Number,
		ReportedAt:    time.Now().Unix(),
		Unit:          user.Company,
		Remark:        form.Remark,
		Province:      user.Province,
		City:          user.City,
		County:        user.County,
		Address:       user.Address,
		Phone:         user.Phone,
		Username:      user.Username,
		Status:        util.PendingStatus,
		UserId:        user.Id,
	}
	if err := db.Create(&report).Error; err != nil {
		return err
	}
	log := entity.ReportLog{UserId: user.Id, Pid: report.Id, CreatedAt: report.ReportedAt, Type: util.TypeDrug}
	table := "report_log_" + strconv.Itoa(int(user.Id%10))
	db.Table(table).Create(&log)

	for _, src := range form.Annexes {
		db.Create(&entity.DrugAnnex{Pid: report.Id, Src: src,})
	}

	// form.UploadAnnexes(ctx, report.Id)
	return nil
}
